<template>
  <div class="headerContainer">
    <div class="partLeft" title="首页">
      <span>Project</span> <SelectProject :logoUrl="ProjectLogo" />
    </div>

    <div class="partRight">
      <!-- 其他工具栏 -->
      <OtherTools :toggleSide="toggleSide" />

      <div>|</div>

      <ControllerWindow />
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import {
  ArrowLeft,
  ArrowRight,
  Operation,
  WarningFilled,
  Minus,
  FullScreen,
  Close,
  MagicStick,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import {
  useProjectStore,
  useThemeStore,
  useOnlineStatusStore,
  useEnduringSseStore,
} from '@/features/store/store'
import ProjectLogo from '@/assets/image/Project.png'
import styles from './header.module.less'
import noOnline from '@/assets/image/noOnline.png'
import { logoutApi } from '@/request/api/master'

// 定义子传父事件
const emit = defineEmits(['toggleAside'])

// 切换侧边栏
const toggleSide = () => emit('toggleAside')

//
//
// 局部选择器组件
const SelectProject = defineComponent({
  props: {
    logoUrl: { type: String, default: '' },
  },
  setup(props) {
    const { projects, projectId } = storeToRefs(useProjectStore())
    const change = (value: string) => useProjectStore().setProjectId(value)

    const onVisibleChange = (v: boolean) => {
      if (v) useProjectStore().resetProjectList()
    }

    return () => (
      <>
        <el-select
          v-model={projectId.value}
          value-key={projectId.value}
          placeholder="Select"
          filterable
          onChange={change}
          style={{ paddingLeft: '10px' }}
          onVisibleChange={onVisibleChange}
        >
          {projects.value.map((item: projectStoreItf) => {
            return (
              <el-option
                key={item.projectId}
                label={item.title}
                value={item.projectId}
              />
            )
          })}
        </el-select>

        <el-image
          title="项目"
          style={{ width: '26px', height: '26px', paddingLeft: '6px' }}
          src={props.logoUrl}
          fit="fill"
        />
      </>
    )
  },
})

//
//
// 局部一些工具按钮组件
const OtherTools = defineComponent({
  props: {
    toggleSide: { type: Function, default: null },
  },
  setup(props) {
    const { onlineStatus } = storeToRefs(useOnlineStatusStore())

    const router = useRouter()
    // 路由历史跳转
    const historyPath = (val: number) => router.go(val)

    // 控制主题的显示与否
    const visible = ref<true | false>(false)

    // 下来菜单点击事件
    const handleCommand = (command: string | number) => {
      const logout = async () => {
        const res = await logoutApi()
        if (res.code !== 200) return ElMessage.error('退出失败！')
        window.localStorage.removeItem('token')
        router.push('/login')
        useEnduringSseStore().closeConnect()
        useProjectStore().resetProjectList()
        useProjectStore().setProjectId('')
      }

      const optionFunc: { [key: string | number]: Function } = {
        theme: () => (visible.value = !visible.value),
        logout: () => logout(),
      }

      optionFunc[command]()
    }

    // 下拉部分组件
    const Dropdown = defineComponent({
      setup() {
        //
        // 主题按钮
        const ThemeButton = defineComponent({
          setup() {
            return () => (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <el-icon color="pink" size="20">
                  <MagicStick />
                </el-icon>
                <b>更换主题</b>
              </div>
            )
          },
        })

        //
        // 主题选项
        const ThemeOptions = defineComponent({
          setup() {
            const { option } = storeToRefs(useThemeStore())

            return () => (
              <div id={styles.themeOptions}>
                {Object.keys(option.value).map((item) => {
                  return (
                    <div onClick={() => useThemeStore().setTheme(item)}>
                      {item.split('-')[1]}
                    </div>
                  )
                })}

                <div>
                  <el-icon size="22" onClick={() => (visible.value = false)}>
                    <Close />
                  </el-icon>
                </div>
              </div>
            )
          },
        })

        return () => (
          <el-dropdown-menu>
            <el-dropdown-item command="theme">
              <el-popover
                placement="left"
                title="主题"
                width="200"
                visible={visible.value}
                show-arrow={false}
                v-slots={{ reference: () => <ThemeButton /> }}
              >
                <ThemeOptions />
              </el-popover>
            </el-dropdown-item>
            <el-dropdown-item command="logout">
              <el-icon color="red" size="20">
                <WarningFilled />
              </el-icon>
              <b>退出登录</b>
            </el-dropdown-item>
          </el-dropdown-menu>
        )
      },
    })

    return () => (
      <div class={styles.OtherToolsContainer}>
        <el-image
          v-show={!onlineStatus.value}
          title="网络未连接"
          style={{ width: '26px', height: '26px', paddingLeft: '6px' }}
          src={noOnline}
          fit="fill"
        />
        <el-icon
          class={styles.icon}
          size="20"
          title="后退"
          onClick={() => historyPath(-1)}
        >
          <ArrowLeft />
        </el-icon>
        <el-icon
          class={styles.icon}
          size="20"
          title="前进"
          onClick={() => historyPath(1)}
        >
          <ArrowRight />
        </el-icon>

        <el-dropdown
          class={styles.icon}
          onCommand={handleCommand}
          v-slots={{ dropdown: () => <Dropdown /> }}
        >
          <el-icon size="22" title="侧边导航栏" onClick={props.toggleSide}>
            <Operation />
          </el-icon>
        </el-dropdown>
      </div>
    )
  },
})

//
//
// 局部控制窗口组件
const ControllerWindow = defineComponent({
  setup() {
    // 最小化窗口
    const minWindow = () => (window as any).controlWindow.minWindow()
    // 切换最大化窗口
    const toggleMaxWindow = () => (window as any).controlWindow.maxWindow()
    // 关闭窗口
    const closeWindow = () => (window as any).controlWindow.closeWindow()

    return () => (
      <div class={styles.ControllerWindowContainer}>
        <el-icon
          class={styles.icon}
          size="24"
          title="最小化"
          onClick={minWindow}
        >
          <Minus />
        </el-icon>
        <el-icon
          class={styles.icon}
          size="20"
          title="全屏"
          onClick={toggleMaxWindow}
        >
          <FullScreen />
        </el-icon>
        <el-icon
          class={styles.icon}
          size="24"
          title="退出"
          onClick={closeWindow}
        >
          <Close />
        </el-icon>
      </div>
    )
  },
})
</script>

<style lang="less" scoped>
@fontstyle: comic Sans MS, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
  Oxygen, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;

.headerContainer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 42px;
  width: calc(100% - 32px);
  padding: 6px 16px;
  font-family: @fontstyle;
  font-weight: bold;
  -webkit-app-region: drag;
  // background-color: #e0e7f8;
  background-color: var(--theme-header);

  > .partLeft {
    -webkit-app-region: no-drag;

    display: flex;
    align-items: center;

    > span {
      cursor: pointer;
    }
  }

  > .partRight {
    display: flex;
    align-items: center;
    -webkit-app-region: no-drag;

    // > * {
    //   margin: 0 8px;
    // }

    // .el-icon {
    //   cursor: pointer;
    //   font-size: 25px;
    //   color: #4f4e4e;
    //   padding: 2px 2px;
    //   border-radius: 4px;
    //   &:hover {
    //     color: black;
    //     background-color: #e0e7f8;
    //     scale: 1.1;
    //   }
    // }
  }
}
</style>
